package com.example.market2023.controller;


import com.example.market2023.entity.Goods;
import com.example.market2023.entity.User;
import com.example.market2023.service.GoodsService;
import com.example.market2023.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class ApiController {

    @Autowired
    UserService userService;

    @Autowired
    GoodsService goodsService;

    @RequestMapping("/login")
    public Integer loginProcess(HttpServletRequest request, @RequestParam String username, @RequestParam String userpwd){
//        首先看有没有接受到数据
        System.out.println(username);
        System.out.println(userpwd);
//        如果传递过来的用户名和密码都正确，就直接进入系统管理的主页面main.html
        User user= new User();
        user.setName(username);
//        从数据库里查询返回的一个用户对象
        User userdb = userService.findOne(user);
        //        如果用户名和密码有错误，然后就去错误提示页面
        if(!userdb.getName().isEmpty()){
            if(userdb.getPassword().equals(userpwd)){
                HttpSession session = request.getSession();
                session.setAttribute("username",username);
                return 1;
            }
            else{
                return 0;
            }
        }else{
            return -1;
        }
    }



    //    处理商品的ajax请求
    @RequestMapping("/goodsDelete")
    public Integer goodsDelete(@RequestParam String id){

//        1.根据获取的id来组装一个goods实体对象
        Goods goods = new Goods();
        goods.setId(Integer.valueOf(id));
//        2.调用service方法处理删除
        if(goodsService.delete(goods)==1){
            return 1;
        }else{
            return 0;
        }
    }

    //   处理更新操作
    @RequestMapping("/goodsUpdateProcess")
    public Integer goodsUpdateProcess(@RequestParam String id,@RequestParam String name,@RequestParam String price,
                                      @RequestParam String quantity,@RequestParam String category,
                                      @RequestParam String supplier){
//        1.组装成goods实体
        Goods goods=new Goods(Integer.valueOf(id),name,Float.valueOf(price),Integer.valueOf(quantity),category,supplier,"0");
        System.out.println(goods);
//       2.调用service里的update方法
        if(goodsService.update(goods)==1){
            return 1;
        }else{
            return 0;
        }
    }}
